<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login_form" :model="loginForm" :rules="rules" ref="formRef">
          <h1>Hello</h1>
          <h2>欢迎来到运营管理平台</h2>
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名" :prefix-icon="User"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              placeholder="请输入密码"
              type="password"
              :prefix-icon="Lock"
              show-password
              @keyup.enter="handleLogin"
            ></el-input>
          </el-form-item>
          <!-- 验证码-->
          <el-form-item prop="code" v-if="captchaEnabled">
            <el-input
              v-model="loginForm.code"
              size="large"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter="handleLogin"
              :prefix-icon="Apple"
            ></el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img" />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="default" class="login_btn" @click="handleLogin" :loading="loading">
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock, Apple } from '@element-plus/icons-vue'
import { ref, reactive } from 'vue'
import { useUserStore } from '@/stores/modules/user'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
import { getTime } from '@/utils/time'
import type { FormRules } from 'element-plus'

// 表单实例
const formRef = ref()

// loading状态
const loading = ref(false)

interface LoginForm {
  username: string
  password: string
  code: string
  uuid: string
}
// 收集登陆用户名和密码
const loginForm = ref<LoginForm>({
  username: '',
  password: '',
  code: '',
  uuid: '',
})

// 表单校验规则
const rules = reactive<FormRules<LoginForm>>({
  username: [{ required: true, validator: validUserName, trigger: 'change' }],
  password: [{ required: true, validator: validPassword, trigger: 'change' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'change' }],
})

// 自定义校验规则
function validUserName(_: any, value: string, callback: any) {
  if (!value) {
    return callback(new Error('请输入用户名'))
  }
  if (value.length < 5) {
    return callback(new Error('用户名长度至少5位'))
  }
  if (value.length > 20) {
    return callback(new Error('用户名长度最多20位'))
  }
  return callback()
}
function validPassword(_: any, value: string, callback: any) {
  if (!value) {
    return callback(new Error('请输入密码'))
  }
  if (value.length < 6) {
    return callback(new Error('密码长度至少6位'))
  }
  if (value.length > 20) {
    return callback(new Error('密码长度最多20位'))
  }
  return callback()
}

// 验证码开关
const captchaEnabled = ref(true)
// 验证码图片
const codeUrl = ref('')

// 获取验证码函数
const getCode = () => {
  useUserStore()
    .imageCode()
    .then((res) => {
      captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
      if (captchaEnabled.value) {
        codeUrl.value = 'data:image/gif;base64,' + res.img
        loginForm.value.uuid = res.uuid
      }
    })
}

// 获取路由器
let $router = useRouter()
let $route = useRoute()

// 处理登陆逻辑
const handleLogin = async () => {
  // 点击登陆按钮以后干什么？
  // 1.收集用户名和密码
  // 2.通知仓库发送登陆请求
  // 3.请求成功 -> 跳转到首页
  // 4.请求失败 -> 弹出登陆失败错误信息

  // 保证表单校验通过再发送登陆请求
  await formRef.value.validate()

  loading.value = true

  try {
    // 可以写.then语法
    await useUserStore().userLogin(loginForm.value)
    // 判断登陆的时候，路由路径当中是否有query参数，如果有就往query参数跳转，如果没有跳转到首页
    const redirect = $route.query.redirect as string
    $router.push({ path: redirect || '/' })
    ElNotification({
      title: `Hi,${getTime()}好`,
      message: '欢迎回来',
      type: 'success',
      duration: 2000,
    })
    loading.value = false
  } catch (error) {
    // 提示错误信息
    ElNotification({
      message: (error as Error).message,
      type: 'error',
      duration: 2000,
    })
    loading.value = false
    // 重新获取验证码
    if (captchaEnabled.value) {
      getCode()
    }
  }
}

// 获取验证码
getCode()

// 获取用户信息
</script>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/bg.jpg') no-repeat center;
  background-size: cover;

  .login_form {
    position: relative;
    top: 20vh;
    width: 60%;
    margin: 0 auto;
    padding: 40px;
    // text-align: center;
    background: url('@/assets/images/login_form.png') no-repeat center;
    // background: blue;
    // opacity: 0.7;
    background-size: cover;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    h1 {
      font-size: 40px;
      color: white;
    }
    h2 {
      font-size: 20px;
      color: white;
      margin: 20px 0;
    }
    .login_btn {
      //   margin-top: 20px;
      width: 100%;
      color: white;
    }
    .login-code {
      width: 33%;
      height: 40px;
      float: right;
      img {
        cursor: pointer;
        vertical-align: middle;
      }
      .login-code-img {
        height: 40px;
        padding-left: 12px;
      }
    }
  }
}
</style>
